<template>
  <el-dialog
    v-model="dialogVisible"
    class="upload-dialog"
    width="800px"
    center
    :close-on-click-modal="false"
    :before-close="cancel"
    @open="handleOpen"
  >
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="影像上传" name="upload" class="upload-pane">
        <div class="upload-tab">
          <el-upload
            :key="+new Date()"
            class="upload-box"
            drag
            action
            :multiple="false"
            :before-upload="handleInvoicePhotoBefore"
            :http-request="uploadRequest"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              拖动文件至此处或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">{{ uploadFileType }}文件，文件大小必须小于1GB</div>
            </template>
          </el-upload>
        </div>
      </el-tab-pane>
      <!-- <el-tab-pane label="影像绑定" name="dicom">
        <div class="btn-wrap">
          <el-button type="primary" size="mini">绑定</el-button>
        </div>
        <ym-table
          v-loading="dicomState.tableLoading"
          select-show
          :data="dicomState.tableData"
          :column-data="columnData"
          :operator-show="false"
          height="412px"
        />
        <pagination
          v-model:currentPage="dicomState.pageObj.pageNum"
          :page-size="dicomState.pageObj.pageSize"
          :total="dicomState.pageObj.total"
          @pagination="getDicomData"
        />
      </el-tab-pane>-->
    </el-tabs>
  </el-dialog>
</template>

<script lang="ts">
export default defineComponent({
  name: 'UploadDialog',
})
</script>

<script lang="ts" setup>
import { computed, defineComponent, defineEmits, defineProps, reactive, ref, watch } from 'vue'

import { ElMessage } from 'element-plus'

import { Pagination, usePage } from '@/components/Pagination/index'
import YmTable from '@/components/YmTable/index.vue'

import EdcApi from '@/api/project/edc'

import { useUserStore } from '@/store/user'

// import ArchiveApi from '@/api/archive'
import { useTween } from '@/utils/common/useTween'

import IBaseObj from '#/index'

const { start } = useTween()

const isComplete = ref(false)

watch(
  () => isComplete.value,
  (val) => {
    if (val) {
      ElMessage.success('文件上传成功，请刷新页面')
      emit('search')
      dialogVisible.value = false
    }
  }
)

const { oid, uid } = useUserStore()

const uploadFileType = 'zip'

// const columnData = [
//   {
//     prop: 'name',
//     label: '受试者'
//   },
//   {
//     prop: 'client',
//     label: '试验中心'
//   },
//   {
//     prop: 'modality',
//     label: '检查技术'
//   },
//   {
//     prop: 'seriesCount',
//     label: '序列数量'
//   }
// ]

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  projectId: {
    type: String,
    default: '',
  },
  visitId: {
    type: [Number, String],
    default: 0,
  },
  centreId: {
    type: [Number, String],
    default: 0,
  },
})

const emit = defineEmits(['update:visible', 'onConfirm', 'search'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val),
})

const activeName = ref('upload') // 默认为上传Tab
watch(
  () => activeName.value,
  (val) => {
    if (val === 'dicom') {
      getDicomData()
    }
  }
)

/** 上传Tab start */

const handleInvoicePhotoBefore = (file: IBaseObj) => {
  const type = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
  if (`.${uploadFileType}` !== type) {
    ElMessage.error(`上传文件的格式不正确，只可上传${uploadFileType}格式的文件`)
    return false
  }
}
const uploadRequest = async (param: IBaseObj) => {
  const formData = new FormData()
  formData.append('file', param.file)
  formData.append('uid', uid)
  formData.append('vid', props.visitId as string)
  const res = await EdcApi.uploadDicomZip(formData, () => {
    start({
      cb: (val: any, total: number) => {
        console.log('t', total)
        param.onProgress({ percent: (val.number / total) * 100 })
      },
      complete: () => {
        isComplete.value = true
      },
    })
    // const num = (progressEvent.loaded / progressEvent.total) * 100
    // param.onProgress({ percent: num })
  })
  if (res) {
    // ElMessage.success('文件上传成功，可刷新查看')
  } else {
    ElMessage.error('文件上传失败，请稍后再上传')
    param.fileList.pop()
  }
}
/** 上传Tab end */

/** 影像绑定Tab start */
const dicomState: IBaseObj = reactive({
  tableLoading: false,
  pageObj: usePage(),
  tableData: [],
})
const getDicomData = async () => {
  dicomState.tableLoading = true
  try {
    const { records, total }: any = await ArchiveApi.getArchiveList({
      inputOrg: oid,
      vid: 0,
      pageSize: dicomState.pageObj.pageSize,
      pageNum: dicomState.pageObj.pageNum,
    })
    dicomState.tableData = records || []
    dicomState.pageObj.total = total || 0
    console.log('d', records, dicomState.tableData)
  } finally {
    dicomState.tableLoading = false
  }
}
/** 影像绑定Tab end */

const cancel = () => {
  dialogVisible.value = false
}

const handleOpen = () => {
  isComplete.value = false
}
</script>

<style lang="scss">
.upload-dialog {
  background: var(--dialog-background-color);

  .el-dialog__title {
    color: var(--color-base);
  }

  .el-form {
    width: 100%;
    padding: 14px 20px 0 20px;
    background: var(--background-color-base);
    border-radius: 6px;

    .el-form-item {
      width: 100%;
    }
  }

  .upload-tab {
    padding-bottom: 20px;

    .el-form {
      width: auto;

      &-item {
        width: auto;
        margin: 18px auto;
      }

      .el-select {
        width: 382px;
      }
    }

    .upload-box {
      display: flex;
      justify-content: center;
      flex-direction: column;

      .el-upload-dragger {
        display: flex;
        justify-content: center;
        flex-direction: column;
        width: 450px;
        height: 240px;
        margin: 0 auto;

        .el-icon-upload {
          margin-top: 0;
        }
      }

      .el-upload__tip {
        text-align: center;
      }

      .el-upload-list__item {
        .el-icon-close {
          display: none;
        }
      }
    }
  }

  .el-progress-bar {
    height: 4px;

    &__outer,
    &__inner {
      height: 4px !important;
    }
  }

  .upload-pane {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .el-tab {
    &-pane {
      height: 500px;
    }
  }
}

// .btn-wrap {
//   line-height: 40px;
//   text-align: right;
// }
</style>
